﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProjectStorageLib.Project;

public partial class controls_SearchProjectsControl : System.Web.UI.UserControl
{
    //manages only one project
    public ProjectManager ProjectManager { get; set; }

    private Dictionary<decimal, decimal> factorValues;

    //manages lists of project managers (i.e. projects) - used for filtering functionality
    public ProjectsManager Manager { get; private set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        factorValues = new Dictionary<decimal, decimal>();
    }

    protected void FactorsScale_IndexChanged(object sender, EventArgs e)
    {
        DropDownList list = (DropDownList)sender;

        System.Web.UI.WebControls.RepeaterItem item =
            (System.Web.UI.WebControls.RepeaterItem)list.Parent;

        HiddenField factorID = (HiddenField)list.Parent.FindControl("m_hfFactorID");

        factorValues.Add(Decimal.Parse(factorID.Value), Decimal.Parse(list.SelectedValue));

        //ProjectManager.SetScaleValueByFactor(
        //    Decimal.Parse(factorID.Value)
        //    , Decimal.Parse(list.SelectedValue)
        //);
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        Session["SearchResult"] = GetResults(factorValues);
        Response.Redirect("~/Commercial/SearchResults.aspx");
    }

    private List<ProjectManager> GetResults(Dictionary<decimal, decimal> factorValues)
    {
        List<ProjectManager> list = new List<ProjectManager>();

        ProjectFilter projectFilter = new ProjectFilter();
        projectFilter.FactorValues = factorValues;
        projectFilter.FactorMandatory = GetMandatoryFactors();
        
        Manager = new ProjectsManager(projectFilter);
        list.AddRange(Manager.GetSimilarProjects().ToList());

        return list;
    }

    private Dictionary<decimal, bool> GetMandatoryFactors()
    {
        Dictionary<decimal, bool> values = new Dictionary<decimal, bool>();
        foreach (RepeaterItem item in m_rptFactorsCategories.Items)
        {
            Repeater repeater = item.FindControl("m_Repeater") as Repeater;
            foreach (RepeaterItem innerItem in repeater.Items)
            {
                HiddenField factorID = (HiddenField)innerItem.FindControl("m_hfFactorID");
                CheckBox factorMandatory = (CheckBox)innerItem.FindControl("chbMandatory");
                values.Add(Decimal.Parse(factorID.Value), factorMandatory.Checked);
            }
        }

        return values;
    }
}